<template>
  <div :class="{'mobile-attachment':showMobilePage}" class="fb-up-attachment">
    <div :class="{'table-upload': tableUpload && fileList && fileList.length > 0}" class="fb-upload-container">
      <el-upload
        v-if="!onlyFileList"
        ref="elUpload"
        :multiple="true"
        :show-file-list="false"
        :http-request="uploadFileMethod"
        :before-upload="beforeUpload"
        :disabled="!isPasteAble"
        :auto-upload="true"
        :class="{'isDisabled': isDisabled}"
        :accept="accept"
        :limit="limit"
        :file-list="fileList || []"
        :on-exceed="handleExceed"
        :on-progress="handleProgress"
        action
        drag
      >
        <template v-if="!$slots.default">
          <div v-if="!titleBg" :class="!isPasteAble && 'upload-disabled'" class="fb-upload-import-btn">
            <i v-if="loading" class="el-icon-loading" style="margin-right:3px;"/>
            <span class="content">拖拽文件或</span>
            <span class="content-link">点击上传</span>
            <img :src="!isPasteAble ? uploadDisabledIcon : downloadIcon" style="width: 16px;height:16px;" alt="上传">
          </div>
          <div v-else>
            <img v-if="bgImg" :src="bgImg" class="bg" alt="">
            <i class="el-icon-plus bg-uploader-icon" />
          </div>
        </template>
        <slot v-else />
      </el-upload>
      <el-tooltip v-if="!hideClipUp" placement="top" effect="dark">
        <div slot="content">
          {{ clipType ? '剪贴板截图上传：点击后，使用粘贴快捷键上传（如：Ctrl+V）': '剪贴板截图上传：点击即可（首次需授权）' }}
        </div>
        <div :disabled="!isPasteAble" :class="[{'has-focus': isBtnFocus}, {'upload-disabled': (!isPasteAble)}, {'table-clip-btn': tableUpload}]" class="clip-btn" @click="obtainClipbrd" @focus="onFocusClip" @blur="onBlurClip">
          <i class="el-icon-s-claim"/>
        </div>
      </el-tooltip>
    </div>
    <slot v-if="$slots.fileList" name="fileList" />
    <ImgShow
      v-else-if="isImgShowMode"
      :is-edit="true"
      :file-percent="filePercent"
      :file-list="fileList"
      :error-file-list="errorFileList"
      show-card-mode
      @removeFile="removeFile"
      @reUpload="reUpload"
      @removeError="removeError"
    />
    <template v-else>
      <div v-if="(fileList && fileList.length > 0) || (errorFileList && errorFileList.length > 0)" :style="{'margin-top': fileContainerTop}" :class="showThumbnail ? 'thumbnail-container' : 'file-container'">
        <template v-if="fileList && fileList.length > 0">
          <div v-for="(item, index) in fileList" :key="index" :class="[{'disabled' : !isReview}, {'upload-img-box' : showThumbnail}]" class="file-item">
            <i v-if="!showThumbnail" class="el-icon-paperclip"/>
            <el-tooltip :open-delay="800" class="item" placement="top" effect="dark">
              <div slot="content" class="tip-content">
                <div class="tip-left">
                  <div class="name" @click="downloadFile(item.url, item.name, true)">文件名：{{ item.name }}</div>
                  <div v-if="item.time" class="time">上传时间：{{ item.time | format('YYYY-MM-DD HH:mm:ss') }}</div>
                </div>
                <span class="tip-right" @click="downloadFile(item.url, item.name, true)">下载</span>
              </div>
              <div v-if="showThumbnail" class="name line-feed-bottom">
                <div style="position: relative">
                  <img :src="item.url" class="upload-img" alt="" @click="downloadFile(item.url, item.name)">
                  <img v-if="!isDisabled" :src="closeImgIcon" class="del-img" alt="" @click="uploadImgDel(item, index)">
                </div>
              </div>
              <div v-else class="name" @click="downloadFile(item.url, item.name)">{{ item.name }}</div>
            </el-tooltip>
            <template v-if="!showThumbnail">
              <div v-if="isDisabled && (isExcel(item.name) || isPdf(item.name))" class="button-text" style="margin-left:5px;" @click="downloadFile(item.url, item.name, true)">下载</div>
              <img v-if="!isDisabled" :src="SuccessIcon" alt="" class="icon-img complete-icon">
              <i v-if="!isDisabled" class="icon el-icon-close" @click="removeFile(item, index)" />
            </template>
          </div>
        </template>
        <template v-if="errorFileList && errorFileList.length > 0">
          <div v-for="(item, index) in errorFileList" :key="'error'+index" :class="showThumbnail && 'upload-img-box'" class="file-item">
            <template v-if="!showThumbnail">
              <i class="el-icon-paperclip"/>
              <div class="name">{{ item.name }}</div>
              <div class="error-text" @click="reUpload(item, index)">重传</div>
              <!-- <i v-if="!isDisabled" class="complete-icon el-icon-circle-close"/> -->
              <img v-if="!isDisabled" :src="ErrorIcon" alt="" class="icon-img complete-icon">
              <i v-if="!isDisabled" class="icon el-icon-close" @click="removeError(item, index)" />
            </template>
            <template v-else>
              <el-tooltip :open-delay="800" placement="top" effect="dark">
                <div slot="content">点击重传</div>
                <div style="position: relative">
                  <img :src="uploadFail" class="upload-img" style="border: 1px solid red;" alt="" @click="reUpload(item, index)">
                  <img :src="closeImgIcon" class="del-img" alt="" @click="uploadImgDel(item, index, true)">
                </div>
              </el-tooltip>
            </template>
          </div>
        </template>
      </div>
    </template>
  </div>
</template>
<script>
import ImportList from './uploadMixins';
import PasteClipboard from '@/mixins/pasteClipboard';
import uploadIcon from '@/assets/export.png';
import downloadIcon from '@/assets/icon-upload-blue.png';
import uploadDisabledIcon from '@/assets/uploading-icon.png';
import uploadFail from '@/assets/upload-fail.png';
import closeImgIcon from '@/assets/close_btn.png';
import { downloadFile, openNewWindow } from '@/utils';
import { format } from '@/filters/date';
import ElMessage from '@/utils/message';
import ImgShow from './imgShowDialog';
import { mapState } from 'vuex';
// img
import SuccessIcon from '@/assets/uploadIcon/success.png';
import ErrorIcon from '@/assets/uploadIcon/error.png';
import * as dd from 'dingtalk-jsapi';
import { getExplorer } from '@/utils/tools';
export default {
  name: 'ImportButton',
  filters: { format },
  components: { ImgShow },
  mixins: [ImportList, PasteClipboard],
  model: {
    prop: 'fileList',
    event: 'changeFileList'
  },
  props: {
    fileList: {
      type: Array,
      default: () => []
    },
    extendParams: {
      type: Object,
      default: null
    },
    // 控制是否显示成功和失败提示框
    hideConfirm: {
      type: Boolean,
      default: false
    },
    // 是否可以点击
    isDisabled: {
      type: Boolean,
      default: false
    },
    isReview: {
      type: Boolean,
      default: true
    },
    isDiy: { // 使用插槽
      type: Boolean,
      default: false
    },
    useOriginName: {
      type: Boolean,
      default: false
    },
    importApi: {
      type: String,
      default: () => {
        return '';
      }
    },
    getList: { // 导入后列表刷新的方法
      type: Function,
      default: null
    },
    onlyFileList: { // 隐藏上传按钮
      type: Boolean,
      default: false
    },
    hideClipUp: { // 隐藏剪切板上传
      type: Boolean,
      default: false
    },
    titleBg: { // 图表标题模块上传背景图
      type: Boolean,
      default: false
    },
    bgImg: { // 图表标题模块上传背景图地址
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 100
    },
    fileContainerTop: {
      type: String,
      default: '10px'
    },
    showThumbnail: { // 是否显示缩略图
      type: Boolean,
      default: false
    },
    maxlength: { // 最多可上传张数
      type: Number,
      default: 9
    },
    tableUpload: {
      type: Boolean,
      default: false
    },
    limitFileSize: {// 最多附件大小
      type: Number,
      default: 50
    },
    uploadType: { // 上传类型：0:通过服务端上传 1:前端直接上传
      type: Number,
      default: 1
    },
    fileType: { // 限制上传的文件类型,以竖线分隔,如jpg|png
      type: String,
      default: ''
    },
    validateUpload: {
      type: Function,
      default: null
    },
    isImgShowMode: { // 是否详细展示图片和视频
      type: Boolean,
      default: false
    },
    useInnerUpload: { // 是否使用内网上传
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      SuccessIcon, ErrorIcon,
      errorFileList: [],
      uploadIcon,
      downloadIcon,
      uploadDisabledIcon,
      uploadFail,
      closeImgIcon,
      limitNum: false,
      fileName: '',
      fileNameCopy: '',
      isUpload: true // 图表标题模块上传背景图是否成功
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isPasteAble() { // pasteClipboard
      const disabledState = this.isDisabled || this.loading;
      if (!this.showThumbnail) {
        return !disabledState;
      }
      return !(disabledState || ((this.fileList.length + this.errorFileList.length) >= this.maxlength));
    },
    overflowRange() {
      const disabledState = this.isDisabled || this.loading;
      if (!this.showThumbnail) {
        return disabledState;
      }
      return disabledState || ((this.fileList.length + this.errorFileList.length) >= this.maxlength);
    }
  },
  created() {
  },
  methods: {
    errorFileListChange(formData, err, originName) {
      this.errorFileList.push({
        formData,
        name: originName || formData.get('fileName')
      });
      this.$emit('upLoadError');
    },
    handleProgress(event, file, fileList) {
      console.log(event, file);
    },
    reUpload(item, index) {
      this.removeError(item, index);
      this.toUploadHttp({ fileObject: item.formData.get('fileData'), fileName: item.name });
    },
    pasteCallback(file) { // pasteClipboard
      const limit = this.limit;
      const fileList = this.fileList;
      if (limit && limit > 0 && fileList && fileList.length >= limit) {
        ElMessage.error(`最多上传${limit}个`);
        return;
      }
      if (this.beforeUpload(file)) this.uploadFileMethod({ file });
    },
    removeError(file, index) {
      this.errorFileList.splice(index, 1);
    },
    removeFile(file, index) {
      this.$emit('removeFileList', { file, index });
    },
    isImg(name) {
      const img = /(\.(gif|png|jpg|jpeg|webp|bmp|tif|pdf))$/i;
      return img.test(name);
    },
    downloadFile(url, name, download = false) {
      if (!this.isReview) return;
      if (download) {
        this.dinkDownload(url, name);
        return;
      }
      if (this.isImg(name)) {
        if (this.isDingTalk()) {
          dd.biz.util.previewImage({
            urls: [url], // 图片地址列表
            current: url, // 当前显示的图片链接
            onFail: function(err) {
              // 调用失败时回调
              window.open(url);
              console.log(err);
            }
          });
        } else {
          window.open(url);
        }
      } else if (this.isExcel(name)) {
        this.viewExcel(url, name);
      } else {
        this.dinkDownload(url, name);
      }
    },
    isPdf(name) {
      const excel = /(\.(pdf))$/i;
      return excel.test(name);
    },
    isExcel(name) {
      const excel = /(\.(doc|docx|xls|xlsx|xlsm|ppt|pptx|txt))$/i;
      return excel.test(name);
    },
    viewExcel(url, name) {
      try {
        // const hangzi = /[\u4e00-\u9fa5]+/g;
        // name = name.replace(hangzi, 'a');
        const timestamp = (new Date()).valueOf();
        const random = Math.ceil(Math.random() * 10);
        const lists = name.split('.');
        const fileName = `${timestamp}${random}.` + lists[lists.length - 1];
        const previewUrl = `${url}#&fullfilename=${fileName}`;
        const officeUrl = 'http://fileview.feibo.com/onlinePreview?url=' + encodeURIComponent(btoa(previewUrl));
        // window.open(officeUrl, '_blank');
        openNewWindow(officeUrl);
        // window.location.href = officeUrl;
      } catch (error) {
        console.log(error);
        this.dinkDownload(url, name);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传${this.limit}个`);
    },
    isDingTalk() {
      const currentExplorer = getExplorer() || window.navigator.userAgent;
      return currentExplorer === 'DingTalk';
    },
    dinkDownload(url, name) {
      if (this.isDingTalk()) {
        // const openUrl = `${window.location.origin}/#/download?fileUrl=${url}&fileName=${name}`;
        dd.biz.util.openLink({
          url: url + '?attname=' + name, // 要打开链接的地址
          onSuccess: function(result) {
            /**/
          }
        });
        // window.open(openUrl, '_blank');
      } else {
        console.log(1111);
        downloadFile(url, name);
        this.$emit('downloadSuccess', name);
      }
    },
    uploadImgDel(file, index, isErrFile = false) {
      if (isErrFile) {
        this.errorFileList.splice(index, 1);
      } else {
        this.removeFile(file, index);
      }
    },
    setPriviewImg(data) {
      if (this.isImgShowMode) {
        // this.$emit('changeFileList', [...this.fileList, {
        //   type: 'preview',
        //   name: data.fileName,
        //   uid: new Date().getTime()
        // }]);
        this.fileList.push({
          type: 'preview',
          name: data.fileName,
          uid: data.fileName
        });
      }
    },
    uploadFinish(fileName) {
      const fileList = this.fileList.filter(item => {
        return !(item.type === 'preview' && item.name === fileName);
      });
      this.$emit('changeFileList', fileList);
    }
  }
};
</script>
<style scoped rel="stylesheet/scss" lang="scss">
.tip-content{
  max-width: 220px;
  display: flex;
  .tip-left{
    .name{
      margin-bottom: 6px;
      cursor: pointer;
      word-break: break-all;
    }
    .time{
      white-space: nowrap;
    }
  }
  .tip-right{
    white-space: nowrap;
    color: #406EFF;
    margin-left: 8px;
    cursor: pointer;
  }
}
.overflow {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 100%;
  display: inline-block;
  text-align: left;
}
.isDisabled {
  opacity: 0.5;
  & ::v-deep {
    .el-upload  {
      cursor: not-allowed;
    }
  }
}
.thumbnail-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .upload-img {
    width: 56px;
    height: 54px;
    margin-right: 12px;
    border-radius: 4px;
    cursor: pointer;
    object-fit: cover;
    box-shadow: 0 2px 6px 0 rgba(211,211,211,1);
    position: relative;
    background-color: transparent;
  }
  .line-feed-bottom {
    margin-bottom: 10px;
  }
  .del-img {
    position: absolute;
    top: -8px;
    right: 4px;
    color: red;
    border-radius: 50%;
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  .upload-img-box {
    ::v-deep .el-tooltip {
      max-height: 54px;
    }
  }
}
.icon-img {
  width: 12px;
}
.fb-up-attachment {
  width: 100%;
  .fb-upload-import-btn {
    width:100%;
    height:32px;
    display: flex;
    align-items: center;
    color: #666666;
    border: 1px dashed #DDDDDD;
    border-radius:4px;
    font-size: 14px;
    padding: 0 8px;
    box-sizing: border-box;
    justify-content: center;
    img {
      width: 16px;
      height: 16px;
      margin-right: 8px;
      position: relative;
    }
    .content-link {
      display: inline-block;
      white-space: nowrap;
      color: #406EFF;
    }
    .content {
      display: inline-block;
      white-space: nowrap;
    }
  }
  .upload-disabled {
    color: #999 !important;
    border: 1px solid #eee !important;
    cursor: not-allowed;
    background-color: #f8f8f8;
  }
  .fb-upload-container {
    position: relative;
    width: 240px;
    &.table-upload{
      border-bottom: 1px solid #EBEEFD;
      margin-bottom: 8px;
    }
  }
  & ::v-deep {
    .el-upload  {
      display: flex;
      &>div {
        align-items: center;
        display: flex;
      }
      .el-upload-dragger {
        height: 32px;
        border: none;
        border-radius: 4px;
        &.is-dragover {
          .fb-upload-import-btn {
            border: 1px dashed #406EFF;
          }
        }
      }
    }
  }
  .clip-btn {
    width: 32px;
    height: 32px;
    background-color: white;
    color: #406EFF;
    border: 1px dashed #DDDDDD;
    border-radius: 0 4px 4px 0;
    border-left: none;
    z-index: 10;
    cursor: pointer;
    z-index: 5;
    position: absolute;
    right: 0px;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    &[disabled=disabled] {
      color: #a1b7ff;
      border: 1px solid #a1b7ff;
      cursor: not-allowed;
    }
    &.table-clip-btn{
      border: none;
    }
  }
  .file-container {
    // margin-top: 10px;
    width: 240px;
    .file-item {
      align-items: center;
      display: flex;
      cursor: pointer;
      padding: 0 5px;
      border-radius: 3px;
      margin-bottom: 3px;
      align-items: center;
      line-height: 1.4;
      &.disabled {
        cursor: not-allowed;
      }
      .el-icon-paperclip {
        font-size: 14px;
        margin-right: 5px;
        color: #909399;
      }
      .complete-icon {
        font-size: 14px;
        &.el-icon-circle-close {
          color: red;
        }
        &.el-icon-circle-check {
          color: #67c23a;
        }
      }
      .error-text {
        color: #406EFF;
        cursor: pointer;
        font-size: 14px;
        margin-right: 5px;
        margin-left: 5px;
      }
      .icon {
        font-size: 14px;
        color: #999;
        cursor: pointer;
        display: none;
      }
      .name {
        font-size: 13px;
        color: #333;
        flex:1;
        // line-height: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 84%;
        &:hover {
          color: #406EFF;
        }
      }
      &:hover {
        background-color: #f5f7fa;
        .icon {
          display: block;
        }
        .complete-icon {
          display: none;
        }
      }
    }
  }
}
.mobile-attachment {
  .fb-upload-container {
    width: 100% !important;
  }
  .file-container {
    width: 100% !important;
  }
  ::v-deep .el-upload-dragger {
    width: 100%;
  }
}
</style>
